package com.eqdd.yiqidian.ui.mine.shenqing;

import android.content.Intent;
import android.databinding.DataBindingUtil;

import com.eqdd.library.percentUtil.WindowUtil;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.ShowMemoActivityCustom;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.CalendarBean;
import com.eqdd.yiqidian.bean.rebuild.MemoListBean;
import com.eqdd.yiqidian.bean.rebuild.MemoResultBean;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.utils.FestivalUtil;
import com.eqdd.yiqidian.utils.Lunar;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.eqdd.yiqidian.widget.CalendarViewGroup;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ShowMemoActivity extends BaseActivity {
    private ShowMemoActivityCustom dataBinding;
    private CalendarBean clickedItem;
    private Map<CalendarBean, SlimAdapterEx> maps = new HashMap<>();
    private SlimAdapterEx slimAdapterMemo;
    private HashMap<String, Integer> colors;


    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_show_memo);
        initTopTitleBar(View.VISIBLE, "备忘录");
        initTopRightText("创建", v -> {
            startActivityForResult(CreateMemoActivity.class, null, Config.CREATE_MEMO);
        });
    }

    @Override
    public void initData() {
        colors = new HashMap<>();
        colors.put("空闲", Color.parseColor("#0000ff"));
        colors.put("暂定", Color.parseColor("#ff8800"));
        colors.put("忙碌", Color.parseColor("#ff0000"));
        colors.put("外出", Color.parseColor("#00ff00"));
        dataBinding.calendarView.setMonthChangeListener((date, data) -> {
            refreshMemoMonth(date, data);
        });
        dataBinding.calendarView.setOnAdapter(new CalendarViewGroup.OnAdapter() {
            @Override
            public RecyclerView.Adapter adpter(RecyclerView recyclerView) {
                final SlimAdapterEx<CalendarBean> slimAdapterEx = SlimAdapterEx.create().registerDefault(R.layout.item_grid_calendar, new SlimInjector<CalendarBean>() {
                    @Override
                    public void onInject(CalendarBean item, IViewInjector injector) {
                        Calendar temp = Calendar.getInstance();
                        temp.setTime(item.getCalendar().getTime());
                        String festival = FestivalUtil.getFestival(temp);
                        Lunar lunar = new Lunar(item.getCalendar());
                        System.out.println(lunar.toString());
                        injector.text(R.id.tv_date_yang, item.getCalendar().get(Calendar.DAY_OF_MONTH) + "")
                                .visibility(R.id.iv_dot, item instanceof MemoListBean ? View.VISIBLE : View.INVISIBLE);
                        if (festival != null) {
                            injector.text(R.id.tv_date_yin, festival);
                        } else {
                            injector.text(R.id.tv_date_yin, new Lunar(item.getCalendar()).get_date());
                        }
                        injector.background(R.id.ll_root, R.color.white);
                        if (item.isClicked()) {
                            injector.textColor(R.id.tv_date_yang, R.color.white)
                                    .textColor(R.id.tv_date_yin, R.color.white);
                            View root = injector.findViewById(R.id.ll_root);
                            root.setBackgroundResource(R.mipmap.red_dot);
                        } else if (item.isToday()) {
                            injector.textColor(R.id.tv_date_yang, R.color.red)
                                    .textColor(R.id.tv_date_yin, R.color.red);
                            View root = injector.findViewById(R.id.ll_root);
                            root.setBackgroundResource(R.mipmap.today_dot);

                        } else if (item.isInMonth()) {
                            injector.textColor(R.id.tv_date_yang, R.color.black)
                                    .textColor(R.id.tv_date_yin, R.color.black);
                        } else {
                            injector.textColor(R.id.tv_date_yang, R.color.green)
                                    .textColor(R.id.tv_date_yin, R.color.green);
                        }
                    }
                });
                ItemClickSupport.addTo(recyclerView)
                        .setOnItemClickListener((recyclerView1, position, v) -> {
                            CalendarBean dataItem = slimAdapterEx.getDataItem(position);
                            if (clickedItem != null && clickedItem != dataItem) {
                                clickedItem.setClicked(false);
                                maps.get(clickedItem).notifyItemChanged(maps.get(clickedItem).getData().indexOf(clickedItem));
                            }
                            if (!dataItem.isClicked()) {
                                dataItem.setClicked(true);
                                slimAdapterEx.notifyItemChanged(position);
                                clickedItem = dataItem;
                                maps.put(clickedItem, slimAdapterEx);
                                refreshMemo(slimAdapterEx.getDataItem(position).getCalendar().getTime());
                            }
                        });

                return slimAdapterEx;
            }

            @Override
            public void notify(RecyclerView.Adapter adapter, List<CalendarBean> data) {
                ((SlimAdapterEx) adapter).updateData(data);
            }
        });

        dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        slimAdapterMemo = SlimAdapterEx.create().register(R.layout.list_item_12, new SlimInjector<MemoResultBean>() {
            @Override
            public void onInject(MemoResultBean data, IViewInjector injector) {
//                data.getStartTime().substring(0, 5)
                injector.text(R.id.tv_upper_left_content, data.getEventName())
                        .text(R.id.tv_upper_right_content, data.getPlace())
                        .text(R.id.tv_down_left_content, data.getStartTime().substring(0, 5) + "~" + data.getEndTime().substring(0, 5))
                        .text(R.id.tv_down_right_content, data.getMemoInfo())
                        .textColor(R.id.tv_upper_left_content, getResources().getColor(R.color.white))
                        .textColor(R.id.tv_upper_right_content, getResources().getColor(R.color.white))
                        .textColor(R.id.tv_down_left_content, getResources().getColor(R.color.white))
                        .textColor(R.id.tv_down_right_content, getResources().getColor(R.color.white))
                        .with(R.id.cardView_root, view -> {
                            CardView cardView = (CardView) view;
                            cardView.setCardBackgroundColor(colors.get(data.getEventType()));
                        });
            }
        }).attachTo(dataBinding.recyclerView).updateData(new ArrayList());

        ItemClickSupport.addTo(dataBinding.recyclerView)
                .setOnItemClickListener((recyclerView, position, v) -> {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("bean", (MemoResultBean) slimAdapterMemo.getDataItem(position));
                    startActivityForResult(CreateMemoActivity.class, bundle, position);
                });


    }

    @Override
    protected void onPause() {
        super.onPause();
        dataBinding.calendarView.pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        dataBinding.calendarView.resume();
    }

    @Override
    public void setView() {
        refreshMemo(new Date());
    }

    private void refreshMemo(Date date) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        OkGo.<HttpResult<List<MemoResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.MEMO_DAY_INFO)
                .params("userGuid", user.getGuid())
                .params("seeDate", simpleDateFormat.format(date))
                .execute(new DialogCallBack<HttpResult<List<MemoResultBean>>>(ShowMemoActivity.this) {
                    @Override
                    public void onSuccess(Response<HttpResult<List<MemoResultBean>>> response) {
                        HttpResult<List<MemoResultBean>> httpResult = response.body();
                        if (httpResult.getStatus() == 200) {
                            slimAdapterMemo.updateData(httpResult.getItems());
                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {

        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Config.SUCCESS) {
            refreshMemo(clickedItem == null ? new Date() : clickedItem.getCalendar().getTime());
            refreshMemoMonth(clickedItem == null ? new Date() : clickedItem.getCalendar().getTime(), null);
        } else if (resultCode == Config.DELETE) {
            slimAdapterMemo.getData().remove(requestCode);
            slimAdapterMemo.notifyItemRemoved(requestCode);
            refreshMemo(clickedItem == null ? new Date() : clickedItem.getCalendar().getTime());
        }
    }

    private void refreshMemoMonth(Date date, List<CalendarBean> data) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        OkGo.<HttpResult<List<String>>>post(HttpConfig.BASE_URL + HttpConfig.MOME_MONTH_LIST)
                .params("userGuid", user.getGuid())
                .params("seeDate", simpleDateFormat.format(date))
                .execute(new DialogCallBack<HttpResult<List<String>>>(ShowMemoActivity.this) {
                    @Override
                    public void onSuccess(Response<HttpResult<List<String>>> response) {
                        HttpResult<List<String>> httpResult = response.body();
                        ArrayList<CalendarBean> calendarBeans = new ArrayList<>();
                        if (httpResult.getStatus() == 200) {
                            if (data != null) {
                                for (int i = 0; i < data.size(); i++) {
                                    for (int j = 0; j < httpResult.getItems().size(); j++) {
                                        if (simpleDateFormat.format(data.get(i).getCalendar().getTime()).equals(httpResult.getItems().get(j))) {
                                            MemoListBean memoListBean = new MemoListBean();
                                            memoListBean.setCalendar(data.get(i).getCalendar());
                                            memoListBean.setClicked(data.get(i).isClicked());
                                            memoListBean.setInMonth(data.get(i).isInMonth());
                                            memoListBean.setToday(data.get(i).isToday());
                                            memoListBean.setEvent(true);
                                            data.remove(i);
                                            data.add(i, memoListBean);
                                            break;
                                        }
                                    }
                                }
                                dataBinding.calendarView.refresh(data);
                            } else {
                                for (String s : httpResult.getItems()) {
                                    MemoListBean calendarBean = new MemoListBean();
                                    Calendar instance = Calendar.getInstance();
                                    try {
                                        instance.setTime(simpleDateFormat.parse(s));
                                        calendarBean.setEvent(true);
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }
                                    calendarBean.setCalendar(instance);
                                    calendarBeans.add(calendarBean);
                                }
                                List<CalendarBean> calendarBeans1 = dataBinding.calendarView.convertData(date, calendarBeans);
                                dataBinding.calendarView.refresh(calendarBeans1);
                            }
                        } else {
                            List<CalendarBean> calendarBeans1 = dataBinding.calendarView.convertData(date, calendarBeans);
                            dataBinding.calendarView.refresh(calendarBeans1);
                        }
                    }

                    @Override
                    public void onError(Response<HttpResult<List<String>>> response) {
                        super.onError(response);
                        List<CalendarBean> calendarBeans1 = dataBinding.calendarView.convertData(date, new ArrayList<CalendarBean>());
                        dataBinding.calendarView.refresh(calendarBeans1);
                    }
                });
    }
}
